package com.armani.controller;

import com.alibaba.fastjson.JSON;
import com.armani.entity.Admin;
import com.armani.model.Result;
import com.armani.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ProjectName: armani
 * @Package: com.armani.controller
 * @ClassName: AdminController
 * @Description: 管理员
 * @Author: lenovo
 * @Date: 2021/11/29 0:35
 * @Version: 1.0
 **/
@Controller
@RequestMapping(value = "admin/", produces = "application/json; charset = utf-8")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @PostMapping(value = "login.do")
    @ResponseBody
    public String login(@RequestParam String user, @RequestParam String password) throws Exception {
        List<Admin> admins = adminService.login(user, password);
        System.out.println(admins);
        Result result = new Result();
        if (admins != null && admins.size() > 0) {
            result.setCode(0);
            result.setMsg("登录成功！");
            result.setData(admins);
        } else {
            result.setCode(1000);
            result.setMsg("用户名或密码错误！");
        }
        String json = JSON.toJSONString(result);
        return json;
    }

    @PostMapping(value = "edit.do")
    @ResponseBody
    @Transactional
    public String edit(@RequestParam(required = false) Integer id,
                       @RequestParam String user,
                       @RequestParam String password,
                       @RequestParam String play,
                       @RequestParam String name,
                       @RequestParam String phone,
                       @RequestParam String power,
                       @RequestParam String state) throws Exception {
        Integer row = 0;
        if (id != null) {
            row = adminService.update(id, user, password, play, name, phone, power, state);
        } else {
            row = adminService.insert(user, password, play, name, phone, power, state);
        }
        Result result = new Result();

        if (row == 0) {
            result.setCode(1000);
            result.setMsg("失败");
        } else {
            result.setCode(0);
            result.setMsg("成功");
        }
        String json = JSON.toJSONString(result);
        return json;
    }

    @PostMapping(value = "del.do")
    @ResponseBody
    @Transactional
    public String del(@RequestParam Integer id) throws Exception {
        Integer row = adminService.del(id);
        Result result = new Result();
        if (row == 0) {
            result.setCode(1000);
            result.setMsg("删除失败！");
        } else {
            result.setCode(0);
            result.setMsg("删除成功！");
        }
        String json = JSON.toJSONString(result);
        return json;
    }
}
